package com.tjs.lucky.application.mq;

import com.alibaba.fastjson.JSON;
import com.tjs.lucky.domain.activity.service.partake.IActivityPartake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.FailureCallback;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.SettableListenableFuture;
import org.springframework.util.concurrent.SuccessCallback;

import javax.annotation.Resource;
import java.util.UUID;

import static com.tjs.lucky.common.Constants.EXCHANGE_NAME;

/**
 * @Author: 田佳澍
 * @Description:
 * @DateTime: 2023/6/10 14:29
 **/
@Component
@Slf4j
public class RabbitMQProducer {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private IActivityPartake activityPartake;


    /**
     * 中奖之后发送，异步发奖
     *
     * @param invoice 中奖信息
     */
    public <T> void sendMessageToLuckyExchange(String queueName, T invoice, String routingKey, ListenableFutureCallback<CorrelationData.Confirm> futureCallback) {
        String message = JSON.toJSONString(invoice);
        log.info("发送MQ消息 queue：{} ; message：{}", queueName, message);
        // 全局唯一的消息ID，需要封装到CorrelationData中
        CorrelationData correlationData = new CorrelationData(routingKey + ":" + UUID.randomUUID().toString());
        SettableListenableFuture<CorrelationData.Confirm> future = correlationData.getFuture();
        future.addCallback(futureCallback);
        // 发送消息
        rabbitTemplate.convertAndSend(EXCHANGE_NAME, routingKey, message, correlationData);
    }

}
